package h5

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"testPaper/common"
	"testPaper/model"
	"testPaper/response"
	"time"
)

// Login 登录
func Login(c *gin.Context) {
	DB := common.GetDB()
	telephone := c.PostForm("telephone")

	if len(telephone) != 11 {
		response.Reponse(c, http.StatusOK, 422, nil, "手机号码不正确")
		return
	}

	var wxUser model.WxUser

	DB.Where("telephone = ?", telephone).First(&wxUser)

	if wxUser.ID != 0 {
		token, err := common.CreatToken(wxUser)
		if err != nil {
			response.Reponse(c, http.StatusOK, 500, nil, "token生成失败")
			return
		}
		if wxUser.UserTime.After(wxUser.CreatedAt) {
			//更新用户登录时间
			DB.First(&wxUser).Update("updated_at", time.Now())
			//登录成功
			response.Reponse(c, http.StatusOK, 200, gin.H{"token": token, "info": wxUser}, "登录成功")
			return
		} else {
			response.Reponse(c, http.StatusOK, 422, nil, "会员时间过期！")
			return
		}
	} else {
		response.Reponse(c, http.StatusOK, 422, nil, "该用户不存在")
		return
	}

}
